package com.mobilesales.android.c2dm.parsers;

import android.content.Context;
import android.util.Log;


public class MessageParser {

	protected Context context;

	public MessageParser(Context context) {
		this.context = context;
	}

	public boolean parseMessage(String message) {
		String[] messageParts = message.split("/");
		
		if (messageParts.length!=3) return false;
		String service = messageParts[0];
		String method = messageParts[1];
		String argument = messageParts[2];
		
		MessageParserBase parser = getParser(service);
		
		if (parser!=null) {
			parser.setContext(context);
			return parser.parseMessage(method, argument);
		}
		return false;
	}
	
	private MessageParserBase getParser(String service) {
		try {
			String clsName = service;
			clsName = clsName.replace("ServiceREST.svc", "");
			clsName = clsName + "MessageParser";
			String packageName = this.getClass().getPackage().getName();
			clsName = packageName + "." + clsName;
			Log.i("MessageParser", "parserType:"+clsName);
			Class<?> parserCls = Class.forName(clsName);
			
			MessageParserBase parser = (MessageParserBase)parserCls.newInstance();
			return parser;			
		}
		catch(Exception ex) {
			Log.e("MessageParser", ex.getMessage(), ex);
			return null;
		}
	}

}
